package com.hqyj.mall.xiaomimall.service.impl;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hqyj.mall.xiaomimall.entity.Users;
import com.hqyj.mall.xiaomimall.mapper.UsersMapper;
import com.hqyj.mall.xiaomimall.service.UsersService;
import com.hqyj.mall.xiaomimall.util.MyUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import javax.annotation.Resource;
import javax.transaction.Transactional;

@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {

    @Resource
    private UsersMapper usersMapper;
    @Override
    public Users login(String identify, String password) {

        Users loginUser = queryUsersByIdentify(identify);
        if(loginUser!=null){
            //判断密码是否正确
            if(MyUtil.validatePassword(password,loginUser.getPassword())){
                return loginUser;
            }else{
                return null;
            }
        }
        return null;
    }

    @Override
    @Transactional(rollbackOn = Exception.class)
    public boolean register(Users u) throws Exception {
        try{
            //对密码进行加密
            u.setPassword(MyUtil.encodePassword(u.getPassword()));
            u.setUsername(MyUtil.generateRandomUsername());
            u.setRegdate(DateUtil.today());

            return super.save(u);
        }catch (Exception ex){
            ex.printStackTrace();
            //手动回滚
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            return false;
        }

    }

    @Override
    public Users queryUsersByUid(Integer uid) {
        return null;
    }

    @Override
    public Users queryUsersByIdentify(String identify) {
        QueryWrapper<Users> queryWrapper = new QueryWrapper<Users>();
        //首先判断一下，你的identify究竟是手机，邮箱还是用户名
        if(MyUtil.isMobileNumber(identify)){
            queryWrapper.eq("mobile",identify);
        }else if(MyUtil.isEmail(identify)){
            queryWrapper.eq("email",identify);
        }else{
            queryWrapper.eq("username",identify);
        }
        return super.getOne(queryWrapper);
    }

    @Override
    public boolean checkIsReg(String identify) {
        return queryUsersByIdentify(identify) != null;
    }
}
